﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Profile;
using System.Text.RegularExpressions;
using System.Text;
using Gift.DAL;
using Gift.Model;

namespace WebSite.cn
{
    public partial class hotpro :  BasePage
    {
        // Fields

        public string STitleName = "";
        public string sPriceName = "";

        const string sCardMenuFormatBegin = " <div class=\"title\" ><a class='{2}' href='{0}' target='_self'>{1}</a></div> "
                                         + " <table><tr> ";
        const string sCardMenuFormatEnd = " </table>";

    
        public string sLoginMessage = "";

        DALShoppro theShoppro = new DALShoppro();
        readonly DALCard theCard = new DALCard();

        DALProfessionAreaType theProfessionType = new DALProfessionAreaType();
        DALShuxintype theShuxin = new DALShuxintype();

                private static readonly Regex RX = new Regex("&amp;page=d+", RegexOptions.Compiled);


              public string ArrowDirectionSale
        {
            get
            {
                if (this.Context.Session["ArrowDirectionSale"] == null)
                {
                    return "&darr;";
                }else
                {
                    return this.Context.Session["ArrowDirectionSale"].ToString();
                }
            }
            set
            {
                this.Context.Session["ArrowDirectionSale"] = value;
            }
        }

       public string ArrowDirectionPrice
       {
           get
           {
               if (this.Context.Session["ArrowDirectionPrice"] == null)
               {
                   return "&darr;";
               }
               else
               {
                   return this.Context.Session["ArrowDirectionPrice"].ToString();
               }
           }
           set
           {
               this.Context.Session["ArrowDirectionPrice"] = value;
           }
       }

  

        // Methods
        private void BindTitle()
        {
            if (!string.IsNullOrEmpty(base.Request.QueryString["sid"]))
            {
                STitleName = theShuxin.GetTitleNameBySid(int.Parse(re.replace(base.Request.QueryString["sid"])));
            }

        }

        public void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if ((base.Request.QueryString["sid"] != null) && ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)))
            {
                Label label = (Label)e.Item.FindControl("price");
                Label label2 = (Label)e.Item.FindControl("Label1");
                Image image = (Image)e.Item.FindControl("Image1");
                if ((label.Text == "0") || (label.Text == "0.00"))
                {
                    label.Text = label2.Text;
                }
                if (image.ImageUrl.ToString() == "")
                {
                    image.ImageUrl = "../uploadfile/banner/" + info.info1("", "shopmopic");
                }
                else
                {
                    image.ImageUrl = "../uploadfile/product/" + image.ImageUrl.ToString();
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Session["backHref"] = Request.Url.PathAndQuery;
            if(!base.IsPostBack)
            {
                if (base.Request.QueryString["sid"] != null)
                {
                    sPriceName = base.Request.QueryString["sid"] == "3" ? "零售价:" : "兑换价:";   
                }
                if (base.Request.QueryString["sid"] != "2")
                {
                    this.divLogin.Visible = false;
                }
    
                this.BindInstitutionDataList();
                this.BindTitle();
                this.AspNetPager1.CurrentPageIndex = 1;
                this.AspNetPager2.CurrentPageIndex = 1;
             
                this.BindProfessionTypeList();
                this.BindDataList(1);
            }
        }

 

         void BindDataList(int iPageType)
        {

            int iCardtypeId = -1;
            if (LoginMember != null && LoginMember.UserCardCodeList != null)
            {
                decimal dTotalCardPrice = 0;
                for (int i = 0; i < LoginMember.UserCardCodeList.Count; i++)
                {
                    dTotalCardPrice += decimal.Parse(LoginMember.UserCardCodeList[i].UserCardPrice);
                }
                this.tdMessage.InnerHtml = "您的礼品卡余额为:" + dTotalCardPrice.ToString() + ",请选取您要购买的商品！";
                this.lbtnExit.Visible = true;
                dbCard oCard = theCard.GetModel(LoginMember.UserCardCodeList[0].UserCardCode, LoginMember.UserCardCodeList[0].UserCardPassword, null);

                iCardtypeId = oCard.cardtypeId;
            }


     
            DataSet ds = theShoppro.GetDataListPage(base.Request.QueryString["sid"]
                                                , Request.QueryString["iid"]
                                                 , Request.QueryString["tid"]
                                                 , Request.QueryString["order"]
                                                 , ArrowDirectionSale
                                                 , ArrowDirectionPrice
                                                 , this.AspNetPager1.StartRecordIndex -1
                                                 , this.AspNetPager1.StartRecordIndex * this.AspNetPager1.PageSize
                                                 , iCardtypeId
                                                 );


            if (ds != null)
            {
                if (iPageType == 1)
                {
                    AspNetPager1.RecordCount = int.Parse(ds.Tables[1].Rows[0][0].ToString());
                    AspNetPager2.RecordCount = AspNetPager1.RecordCount;
                }
                else if (iPageType == 2)
                {
                    AspNetPager2.RecordCount = int.Parse(ds.Tables[1].Rows[0][0].ToString());
                    AspNetPager1.RecordCount = AspNetPager2.RecordCount;
                }
                this.productsList.DataSource = ds.Tables[0].DefaultView;
                this.productsList.DataBind();
            }


            this.tdOrder.InnerHtml = BuilderOutPageHeaderHtml;
        }


         public string BuilderOutPageHeaderHtml
         {
             get
             {
                 string input = this.Context.Request.Url.Query.Replace("?", "&amp;");
                 input = RX.Replace(input, string.Empty);
                 input = input.Replace("&amp;order=sale", string.Empty);
                 input = input.Replace("&amp;order=price", string.Empty);
                 input = input.Replace("&amp;order=time", string.Empty);
                 string sLiClass1 = string.Empty;
                 string sLiClass2 = string.Empty;
                 string sLiClass3 = string.Empty;
                 string sArrow1 = string.Empty;
                 string sArrow2 = string.Empty;
                 if (string.IsNullOrEmpty(this.Context.Request["order"]) || this.Context.Request["order"] == "sale")
                 {
                     if (!string.IsNullOrEmpty(this.Context.Request["order"]))
                     {
                         if (ArrowDirectionSale == "&darr;")
                         {
                             ArrowDirectionSale = "&uarr;";
                         }
                         else
                         {
                             ArrowDirectionSale = "&darr;";
                         }
                     }
                     sArrow1 = ArrowDirectionSale;
                     sLiClass1 = "class='currentPage'";
                     sArrow2 = string.Empty;
                 }
                 else if (this.Context.Request["order"] == "price")
                 {
                     if (ArrowDirectionPrice == "&darr;")
                     {
                         ArrowDirectionPrice = "&uarr;";
                     }
                     else
                     {
                         ArrowDirectionPrice = "&darr;";
                     }
                     sArrow2 = ArrowDirectionPrice;
                     sArrow1 = string.Empty;
                     sLiClass2 = "class='currentPage'";
                 }
                 else if (this.Context.Request["order"] == "time")
                 {
                     sLiClass3 = "class='currentPage'";
                 }
                 StringBuilder sbPageHeader = new StringBuilder();
                 sbPageHeader.Append("  <div style=\" width:100%; text-align:left;  height:19px; padding-left:5px; float:left\">");
                 sbPageHeader.Append("  <div>排序</div>");
                 sbPageHeader.Append("   <div id=\"orderMenu\">");
                 sbPageHeader.Append("  <ul>");
                 sbPageHeader.Append(string.Format("  <li {1}><a href=?order=sale{0}>{4}销  量</a></li><li {2}><a href=?order=price{0}>{5}价  格</a></li><li {3}><a href=?order=time{0}>上价时间</a></li>", input, sLiClass1, sLiClass2, sLiClass3, sArrow1, sArrow2));
                 sbPageHeader.Append("  </ul>");
                 sbPageHeader.Append("  </div>");

                 sbPageHeader.Append(" </div>");

                 return sbPageHeader.ToString();
                 //System.Web.UI.HtmlControls.HtmlGenericControl divHtml = new System.Web.UI.HtmlControls.HtmlGenericControl();
                 //divHtml.InnerHtml = sbPageHeader.ToString();
             }
         }

        void BindInstitutionDataList()
        {
            DALInstitution theInstitution = new DALInstitution();
            List<tbInstitution> lstInstitution = theInstitution.GetInstitutionDataList();
         
            int currentId = 0;
            if (!string.IsNullOrEmpty(Request.QueryString["iId"]))
            {
                currentId = int.Parse(Request.QueryString["iId"]);
            }

            string input = this.Context.Request.Url.ToString();
            input = Regex.Replace(input, "&amp;iId=[-]?[0-9]+", string.Empty);
            input = Regex.Replace(input, "&iId=[-]?[0-9]+", string.Empty);

            input = Regex.Replace(input, "&amp;tId=[-]?[0-9]+", string.Empty);
            input = Regex.Replace(input, "&tId=[-]?[0-9]+", string.Empty);

            StringBuilder sbCardList = new StringBuilder();
            List<tbProfessionAreaType> lstProType = theProfessionType.getAllList();
            List<tbProfessionAreaType> lstTempProType = null;
            int iCount = 0;
            foreach(var o in lstInstitution)
            {
                if (lstProType != null)
                {
                    lstTempProType = lstProType.FindAll(item => item.InstitutionId == o.Id);
                    if (lstTempProType != null && lstTempProType.Count >0)
                    {
                        string sCssClass = string.Empty;

                        if (!string.IsNullOrEmpty(Request.QueryString["iId"]) && Request.QueryString["iId"] == o.Id.ToString())
                        {
                            sCssClass = "currentInstitution";
                        }

                        sbCardList.Append(string.Format(sCardMenuFormatBegin, input + "&iId=" + o.Id.ToString(), o.Name, sCssClass));
                        iCount = 1;

                        string sCurrentAreaTypeCss = string.Empty;
                        foreach (var tempType in lstTempProType)
                        {
                            if (!string.IsNullOrEmpty(Request.QueryString["tId"]) && Request.QueryString["tId"] == tempType.Id.ToString())
                            {
                                sCurrentAreaTypeCss = "currentProfessionAreaType";
                            }
                            else
                            {
                                sCurrentAreaTypeCss = string.Empty;
                            }

                            if (iCount % 7 == 0)
                            {
                                sbCardList.Append(string.Format("<td><a href='{0}' class='{1}' target='_self'>{2}</a></td></tr>"
                                                          , input + "&tId=" + tempType.Id.ToString() + "&iId=" + o.Id.ToString()
                                                          , sCurrentAreaTypeCss
                                                          ,tempType.Name));
                            }
                            else if (iCount == lstTempProType.Count)
                            {
                                sbCardList.Append(string.Format("<td colspan='{0}'><a href='{1}' class='{2}' target='_self'>{3}</a></td></tr>"
                                                                 , (8 - iCount % 7).ToString()
                                                                 , input + "&tId=" + tempType.Id.ToString() + "&iId=" + o.Id.ToString()
                                                                 , sCurrentAreaTypeCss
                                                                 ,tempType.Name));
                            }
                            else
                            {
                                sbCardList.Append(string.Format("<td style='width:14%'><a href='{0}' class='{1}' target='_self'>{2}</a></td>"
                                                                 , input + "&tId=" + tempType.Id.ToString() + "&iId=" + o.Id.ToString()
                                                                 , sCurrentAreaTypeCss
                                                                 , tempType.Name));
                            }
                            iCount++;
                        }

                        sbCardList.Append(sCardMenuFormatEnd);   
                    }
 
                }
        
                //if (o.Id == currentId)
                //{
                //    o.Name = string.Format("<div class='currentInstitution'> <a href={0} >{1} </a></div>", input + "&institutionId=" + o.Id.ToString(), o.Name);
                //}
                //else
                //{
                //    o.Name = string.Format("<div> <a href={0} >{1} </a></div>", input + "&institutionId=" + o.Id.ToString(), o.Name);
                //}
            }
            this.institutionMenu.InnerHtml = sbCardList.ToString();

            //this.dlist.DataSource = lstInstitution;
            //this.dlist.DataBind();
        }

        protected void AspNetPager1_PageChanged(object src, EventArgs e)
        {
            this.AspNetPager2.CurrentPageIndex = this.AspNetPager1.CurrentPageIndex;
            this.BindDataList(1);
          
        }

        protected void AspNetPager2_PageChanged(object src, EventArgs e)
        {
            this.AspNetPager1.CurrentPageIndex = this.AspNetPager2.CurrentPageIndex;
            this.BindDataList(2);

        }

        void BindProfessionTypeList()
        {
            int institutionId = -1;
            if(!string.IsNullOrEmpty(this.Request.QueryString["iId"]))
            {
                institutionId = int.Parse(this.Request.QueryString["iId"]);
             
            }
            List<tbProfessionAreaType> lstAreaType = theProfessionType.getListByInstitutionId(institutionId);
            //this.dlProfessionList.DataSource = lstAreaType;
            //this.dlProfessionList.DataBind();
         
        }

        protected void btnAddCard_Click(object sender, EventArgs e)
        {
            this.ulErrorMessage.Visible = false;
            if (this.txtCardCode.Text.Trim() == string.Empty)
            {
                this.liErrorMessage.InnerHtml = "卡号不能为空！";
                this.ulErrorMessage.Visible = true;
                return;
            }

            if (this.txtPassword.Text.Trim() == string.Empty)
            {
                this.liErrorMessage.InnerHtml = "密码不能为空！";
                this.ulErrorMessage.Visible = true;
                return;
            }

            if (this.txtValidate.Text.Trim() == string.Empty)
            {
                this.liErrorMessage.InnerHtml = "验证码不能为空！";
                this.ulErrorMessage.Visible = true;
                return;
            }
            
            
         
            if (string.Compare(this.txtValidate.Text.Trim(), Session["checkCode"].ToString()) != 0)
            {
                this.liErrorMessage.InnerHtml = "验证码不正确！请重新输入！";
                this.ulErrorMessage.Visible = true;
                return;
            }

            dbCard oCard;
            oCard = theCard.GetModel(this.txtCardCode.Text.Trim(), this.txtPassword.Text.Trim(), null);
            if (oCard != null)
            {
                if (oCard.states == 0)
                {
                  
                    this.liErrorMessage.InnerHtml = "该卡还未激活，请先开卡后才能使用！";
                    this.ulErrorMessage.Visible = true;
                    return;
                }
                else if (oCard.states == 2)
                {
                    this.liErrorMessage.InnerHtml = "该卡已被使用！";
                    this.ulErrorMessage.Visible = true;
                    return;
                }
                else if (oCard.states == 3)
                {
                 
                    this.liErrorMessage.InnerHtml = "该卡已失效！";
                    this.ulErrorMessage.Visible = true;
                    return;

                }
                else if (oCard.states == 4)
                {
                
                    this.liErrorMessage.InnerHtml = "该卡还未激活,请先开卡后才能使用！";
                    this.ulErrorMessage.Visible = true;
                    return;

                }
                else if (oCard.endtime < DateTime.Now.Date)
                {
                    if (oCard.lasttime >= DateTime.Now.Date)
                    {
                        this.liErrorMessage.InnerHtml = "该卡的专区有效时间已过,只能到礼品商城兑换商品！";
                        this.ulErrorMessage.Visible = true;
                        return;
                    }
                    else
                    {
                        this.liErrorMessage.InnerHtml = "该卡已失效！";
                        this.ulErrorMessage.Visible = true;
                        return;
                    }
                }
                else if (oCard.states == 1)
                {
                    if (LoginMember == null)
                    {
                        return;
                    }
                   
                    if (LoginMember.UserCardCodeList != null)
                    {
                        UserCard oCard1 = new UserCard();
                        DALCard oCardCampa = new DALCard();
                        if (LoginMember.UserCardCodeList[0].UserCardTypeId == oCard.cardtypeId.ToString())
                        {
                            UserCard tempCard = LoginMember.UserCardCodeList.Find(item => item.UserCardCode == txtCardCode.Text.Trim());

                            if (tempCard == null)
                            {
                                oCard1.UserCardId = oCard.cardid.ToString();
                                oCard1.UserCardCode = txtCardCode.Text.Trim();
                                oCard1.UserCardPassword = txtPassword.Text.Trim();
                                oCard1.UserCardPrice = oCard.cardprice.ToString();
                                oCard1.UserCardTypeId = oCard.cardtypeId.ToString();
                                oCard1.ProfessionAreaTypeId = oCard.ProfessionAreaTypeId;
                                LoginMember.UserCardCodeList.Add(oCard1);
                            }
                        }
                        else
                        {            
                            this.liErrorMessage.InnerHtml = "只能添加同类卡！";
                            this.ulErrorMessage.Visible = true;
                            return;
                        }
                    }
                    else
                    {
                        LoginMember.UserCardCodeList = new List<UserCard>();
                        UserCard oCard2 = new UserCard();
                        oCard2.UserCardId = oCard.cardid.ToString();
                        oCard2.UserCardCode = txtCardCode.Text.Trim();
                        oCard2.UserCardPassword = txtPassword.Text.Trim();
                        oCard2.UserCardPrice = oCard.cardprice.ToString();
                        oCard2.UserCardTypeId = oCard.cardtypeId.ToString();
                        oCard2.ProfessionAreaTypeId = oCard.ProfessionAreaTypeId;
                        LoginMember.UserCardCodeList.Add(oCard2);
                    }

                    this.lbtnExit.Visible = true;


                    if (!string.IsNullOrEmpty(Request.QueryString["pid"]))
                    {
                        DataTable table;
                        string str2;
       
                        string strPrice = "0";
                        string strContent = "";
                        string strProdNum = "0";
                        string strPid = "";
                        strPid = base.Request.QueryString["pid"];
                        strPrice = base.Request.QueryString["price"].ToString();
                        strContent = base.Request.QueryString["content"].ToString();
                        strProdNum = base.Request.QueryString["pronum"].ToString();

                        string tempId = string.Empty;
                        if (LoginMember.UserCardCodeList != null)
                        {
                            tempId = LoginMember.UserCardCodeList[0].UserCardCode;
                        }
                        else if (LoginMember != null)
                        {
                            tempId = LoginMember.MemberId.ToString();
                        }
                        else
                        {
                            tempId = re.ReadCookie("tempno");
                        }
                        if (string.IsNullOrEmpty(tempId))
                        {
                            tempId = "0";
                        }

                        table = SQLAccess.GreatDs("select top 1 carid,pronum,price,score from DB_Car where productid=" + strPid + " and temp=" + tempId + " and contents='" + strContent + "' and flag=0").Tables[0];
                        if (table.Rows.Count > 0)
                        {
                            str2 = "update DB_Car set pronum=" + strProdNum + ",sumprice=" + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(table.Rows[0]["price"]))) + ",sumscore=" + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(table.Rows[0]["score"]))) + " where carid=" + table.Rows[0]["carid"].ToString() + "";
                        }
                        else
                        {
                            str2 = "insert into DB_Car (productid,memberid,pronum,state,flag,price,contents,temp,sumprice,score,sumscore) values (" + strPid + ",0," + strProdNum + ",0,0," + strPrice + ",'" + strContent + "'," + tempId + "," + Convert.ToString((float)(Convert.ToSingle(strProdNum) * Convert.ToSingle(strPrice))) + ",0,0)";
                        }
                        SQLAccess.DoSql(str2);
                        base.Response.Write("<script language='javascript'>window.location.href='account.aspx?type=1';</script>");
                        base.Response.End();

                    }
                    this.BindDataList(1);
                }
                else
                {
                    this.liErrorMessage.InnerHtml = "该卡已被使用！";
                    this.ulErrorMessage.Visible = true;
                    return;
                }
            }
            else
            {
                this.liErrorMessage.InnerHtml = "卡号或密码不正确！";
                this.ulErrorMessage.Visible = true;
                return;
            }
        }

        protected void lbtnExit_Click(object sender, EventArgs e)
        {
            if (base.LoginMember != null && LoginMember.UserCardCodeList != null)
            {
                base.LoginMember.UserCardCodeList = null;

                Response.Redirect("index.aspx");
            }
        }



    }
}